package com.atguigu.flink.chapter08;

import com.atguigu.flink.bean.OrderEvent;
import com.atguigu.flink.util.AtguiguUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.EventTimeSessionWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;
import java.util.List;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/10/19 9:12
 */
public class Flink06_Project_High_Order {
    public static void main(String[] args) throws Exception {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 2000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
    
        env
            .readTextFile("input/OrderLog.csv")
            .map(line -> {
                String[] data = line.split(",");
                return new OrderEvent(Long.valueOf(data[0]),
                                      data[1],
                                      data[2],
                                      Long.parseLong(data[3]) * 1000);
            })
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<OrderEvent>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                    .withTimestampAssigner((event, ts) -> event.getEventTime())
            )
            .keyBy(OrderEvent::getOrderId)
            .window(EventTimeSessionWindows.withGap(Time.minutes(45)))
            .process(new ProcessWindowFunction<OrderEvent, String, Long, TimeWindow>() {
    
                private ValueState<OrderEvent> createState;
    
                @Override
                public void open(Configuration parameters) throws Exception {
                    createState = getRuntimeContext().getState(new ValueStateDescriptor<OrderEvent>("createState", OrderEvent.class));
                }
    
                @Override
                public void process(Long key,
                                    Context context,
                                    Iterable<OrderEvent> elements,
                                    Collector<String> out) throws Exception {
                    /*
                    如果订单创建和支付都正常情况: 则集合中有两个元素
                    
                    1. 如果只有一个create, 则表示没有pay, 或者pay的时间超过了45分钟
                    
                    2. 只有一个pay,  ?
                    
                     */
                    List<OrderEvent> events = AtguiguUtil.toList(elements);
                    if (events.size() == 2) {
                        out.collect("订单:" + key + " 正常");
                    }else{
                        // 如果长度不是2则, 一定是1
                        OrderEvent event = events.get(0);
                        if ("create".equals(event.getEventType())) {
                            // 这个session窗口只有create, 没有pay: 要没有真的的没有pay, 要么pay超时了
                            createState.update(event);
                            // 假设结果写入到mysql: 可以先在mysql中输入只有create没有pay
                            // 没法判断未来pay的情况
                        }else{
                            // Pay来来了: 1. pay迟到来的  2. 没有create只有pay
                            if(createState.value() != null){
                                // 表示create来过, 但是pay晚于create超过了45分钟,他们没有在同一个窗口中
                                out.collect("订单:" + key + " 超时支付, 请检测系统漏洞");
                            }else{
                                out.collect("订单:" + key + " 只有pay没有create, 请检测系统漏洞");
                            }
                        }
                    }
    
                }
            })
            .print();
    
        env.execute();
        
    }
}
